package com.jack.screenprojectionpushsimple

import android.media.projection.MediaProjection
import org.java_websocket.WebSocket
import org.java_websocket.handshake.ClientHandshake
import org.java_websocket.server.WebSocketServer
import java.io.IOException
import java.net.InetSocketAddress

/**
 * @创建者 Jack
 * @创建时间 2024/1/13 9:08
 * @描述
 */
class SocketClient(port: Int, width: Int, height: Int) {
    private var mWebSocket: WebSocket? = null
    private var mWidth: Int
    private var mHeight: Int

    init {
        mWidth = width
        mHeight = height
    }

    private val mWebSocketServer = object : WebSocketServer(InetSocketAddress(port)) {
        override fun onOpen(conn: WebSocket, handshake: ClientHandshake) {
            println("WebSocketServer onOpen1 ${conn == null}")
            this@SocketClient.mWebSocket = conn
            println("WebSocketServer onOpen")
        }

        override fun onClose(conn: WebSocket, code: Int, reason: String, remote: Boolean) {
            println("WebSocketServer onClose")
        }

        override fun onMessage(conn: WebSocket, message: String) {
            println("WebSocketServer onMessage")
        }

        override fun onError(conn: WebSocket, ex: Exception) {
            println("WebSocketServer onError")
        }

        override fun onStart() {
            println("WebSocketServer onStart")
        }
    }

    fun start(mediaProjection: MediaProjection) {
        mWebSocketServer.start()
        val h265Encoder = H265Encoder(mediaProjection, this, mWidth, mHeight)
        h265Encoder.startPush()
    }

    fun pushData(bytes: ByteArray?) {
        if (mWebSocket?.isOpen == true) {
            mWebSocket?.send(bytes)
        }
    }

    fun close() {
        try {
            mWebSocket?.close()
            mWebSocketServer.stop()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }
}